<template>
    <!-- 可以上传头像 -->
    <div text-16 text-dark mx-auto pt-15 text-center dark:text-white>
        <van-dialog v-model:show="localVisible" :showConfirmButton="false" width="88%">
            <!-- <img src="/img/close.png" alt="" class="w-16 absolute top-10 right-10 m-5" @click="handleClose"> -->
            <div class="w-full text-right px-15 pt-10">
                <van-icon name="cross" color="#999" size="20" @click="handleClose" />
            </div>
            <van-uploader ref="uploaderRef" v-if="!showImage" :after-read="afterRead" />
            <img v-if="showImage" :src="imageUrl" class=" w-66 h-66 rounded-full mx-auto " @click="triggerUpload" />
            <div class="my-10 text-12 color-#ffffff">点击头像可上传图片</div>
            <div class="text-left pl-17 color-#ffffff text-14">更换头像</div>
            <div class="grid grid-cols-4 gap-10 mt-2 place-items-center p-10">
                <!-- <img :src="item.img" v-for="item in imgs" :key="item.id" alt="" @click="toggleSelect(item.id)"
                    class="item-img w-50 h-50 rounded-full p-1" :class="{ 'selected': selectedId === item.id }" /> -->
                <van-image width="50" height="50" lazy-load class="item-img rounded-full p-1"
                    :class="{ 'selected': selectedId === item.id }" :src="item.img" v-for="item in imgs" :key="item.id"
                    @click="toggleSelect(item.id)">
                    <template v-slot:loading>
                        <van-loading type="spinner" size="20" />
                    </template></van-image>
            </div>
            <div @click="submit" class="btn w-90% mx-auto py-10 text-center text-14  rounded-5 mb-20 mt-10"
                :class="(selectedId != null || (imageUrl && selectedId === null)) ? 'active' : ''">确认更换
            </div>
        </van-dialog>
    </div>
</template>

<script setup lang="ts">
const props = defineProps({
    visible: {
        type: Boolean,
        required: true
    }
})
const emit = defineEmits(['update:visible', 'updateAvatar'])
const userStore = useUserStore()
const selectedId = ref<number>(null) // -1 表示未选中
const imageUrl = ref<string>('');
const showImage = ref<boolean>(true);
const imgs = ref([
    { id: 0, img: '/imgs/head1.png' },
    { id: 1, img: '/imgs/head2.png' },
    { id: 2, img: '/imgs/head3.png' },
    { id: 3, img: '/imgs/head4.png' },
    { id: 4, img: '/imgs/head5.png' },
    { id: 5, img: '/imgs/head6.png' },
    { id: 6, img: '/imgs/head7.png' },
    { id: 7, img: '/imgs/head8.png' },
    { id: 8, img: '/imgs/head9.png' },
    { id: 9, img: '/imgs/head10.png' },
    { id: 10, img: '/imgs/head11.png' },
    { id: 11, img: '/imgs/head12.png' },
    { id: 12, img: '/imgs/head13.png' },
    { id: 13, img: '/imgs/head14.png' },
    { id: 14, img: '/imgs/head15.png' },
])
// 本地变量控制弹窗状态
const localVisible = ref(props.visible)
// 当 props.visible 变化时同步到本地
watch(
    () => props.visible,
    (newVal) => {
        localVisible.value = newVal
    }
)
const uploaderRef = ref(null)

const triggerUpload = async () => {
    showImage.value = false
    // 等待 DOM 更新后获取元素
    await nextTick()

    if (uploaderRef.value) {
        const fileInput = uploaderRef.value.$el.querySelector('input[type="file"]')
        if (fileInput) {
            fileInput.click()
        } else {
            console.warn('未找到文件选择框')
        }
    } else {
        console.error('uploaderRef 未正确绑定')
    }
}
onMounted(() => {
    imageUrl.value = userStore.user.avatar
})
const toggleSelect = (id: number) => {
    selectedId.value = selectedId.value === id ? null : id
    imageUrl.value = imgs.value.find(v => v.id === selectedId.value).img
}
const handleClose = () => {
    emit('update:visible', false)
}
const submit = () => {
    const selectedItem = imgs.value.find(v => v.id === selectedId.value)
    if (selectedItem) {
        emit('updateAvatar', selectedItem.img)
    } else {
        emit('updateAvatar', imageUrl.value)
    }
}
const afterRead = (file: UploaderFileListItem | UploaderFileListItem[]) => {
    if (Array.isArray(file)) {
        handleFile(file[0]);
    } else {
        handleFile(file);
    }
};
// 上传图片
const handleFile = (fileItem: UploaderFileListItem) => {
    if (fileItem.file) {
        const reader = new FileReader();
        reader.onload = (e) => {
            imageUrl.value = e.target?.result as string;
            showImage.value = true;
        };
        reader.readAsDataURL(fileItem.file);
    } else {
        console.error('上传的文件无效');
    }
};
</script>

<style lang="css" scoped>
::v-deep .van-dialog {
    background: #2a2a2a;
}

/* ::v-deep .van-icon {
    background: #2a2a2a;
    right: 10px;
    top: 10px;
} */

::v-deep .van-uploader__upload {
    border-radius: 100%;
    margin-top: 20px;
    width: 66px;
    height: 66px;
}

.item-img {
    box-sizing: border-box;
}

.item-img.selected {
    border: 1px solid #2cfa87;
    box-shadow:
        0 0 2px 2px rgba(44, 250, 135, 0.5),
        0 0 3px 3px rgba(44, 250, 135, 0.3),
        0 0 5px 5px rgba(44, 250, 135, 0.1);
    /* box-shadow: 0 0 1px 1px rgba(44, 250, 135, 0.7);
  animation: pulse 1.5s infinite; */
}

@keyframes pulse {
    0% {
        box-shadow: 0 0 1px 1px rgba(44, 250, 135, 0.7);
    }

    50% {
        box-shadow: 0 0 2px 2px rgba(rgba(44, 250, 135, 0.7));
    }

    100% {
        box-shadow: 0 0 1px 1px rgba(44, 250, 135, 0.7);
    }
}

.btn {
    background: #d9d8d4;
    color: #9e9b98;
}

.active {
    color: #ffffff;
    background-image: linear-gradient(0deg,
            #077cfe 0%,
            #0470eb 100%),
        linear-gradient(#d9d8d4,
            #d9d8d4);
}

::v-deep .van-image__error,
.van-image__loading {
    border-radius: 50%;
}
::v-deep .van-image{
    border-radius: 50%;
}
</style>